package com.sfac.springBoot.filter;

import org.apache.tomcat.util.buf.Ascii;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * personal demo
 **/
@WebFilter(urlPatterns = "/*",filterName = "parameterFilter")
public class parameterFilter implements Filter {// package servlet

    public final static Logger LOGGER= LoggerFactory.getLogger(parameterFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("init============================");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        LOGGER.debug("doing============================");
        HttpServletRequest req = (HttpServletRequest) servletRequest;


        HttpServletRequestWrapper hrw = new HttpServletRequestWrapper(req){
            @Override
            public String getParameter(String name) {
                String val = super.getParameter(name);
                if(val.contains("fuck")){
                    val = val.replaceAll("fuck", "***");
                }
                return  val;
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);
                String[] res = new String[values.length];
                for(int i=0;i<values.length;i++){
                    String temp=values[i];
                    if(values[i].contains("fuck")){
                        temp = values[i].replace("fuck", "****");
                    }
                    res[i]=temp;
                }
                return res;

            }
        };



        filterChain.doFilter(hrw, servletResponse);
    }

    @Override
    public void destroy() {
        LOGGER.debug("dest============================");

    }
}
